<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>基于pdf.js的前后端分离式PDF文件预览实现 | LenlBlog</title><meta name="author" content="Lenl,lenl412@163.com"><meta name="copyright" content="Lenl"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="基于SpringBoot+Vue+pdf.js的pdf预览实现">
<meta property="og:type" content="article">
<meta property="og:title" content="基于pdf.js的前后端分离式PDF文件预览实现">
<meta property="og:url" content="https://lienle.gitee.io/notes/PdfView/index.html">
<meta property="og:site_name" content="LenlBlog">
<meta property="og:description" content="基于SpringBoot+Vue+pdf.js的pdf预览实现">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://z4a.net/images/2023/04/22/fcc1d07f3136fe8e818242a6534391c8.md.png">
<meta property="article:published_time" content="2023-08-06T02:18:26.000Z">
<meta property="article:modified_time" content="2023-08-06T03:38:13.513Z">
<meta property="article:author" content="Lenl">
<meta property="article:tag" content="SpringBoot">
<meta property="article:tag" content="Vue">
<meta property="article:tag" content="PDF">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://z4a.net/images/2023/04/22/fcc1d07f3136fe8e818242a6534391c8.md.png"><link rel="shortcut icon" href="/img/lenl.png"><link rel="canonical" href="https://lienle.gitee.io/notes/PdfView/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="baidu-site-verification" content="codeva-6HME93uF43"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?629608ec0c773bd9f96cb72389693ab9";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: Lenl","link":"链接: ","source":"来源: LenlBlog","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '基于pdf.js的前后端分离式PDF文件预览实现',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-08-06 11:38:13'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script></head><body><!--include ./fullpage-loading.pug--><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="wizard-scene"><div class="wizard-objects"><div class="wizard-square"></div><div class="wizard-circle"></div><div class="wizard-triangle"></div></div><div class="wizard"><div class="wizard-body"></div><div class="wizard-right-arm"><div class="wizard-right-hand"></div></div><div class="wizard-left-arm"><div class="wizard-left-hand"></div></div><div class="wizard-head"><div class="wizard-beard"></div><div class="wizard-face"><div class="wizard-adds"></div></div><div class="wizard-hat"><div class="wizard-hat-of-the-hat"></div><div class="wizard-four-point-star --first"></div><div class="wizard-four-point-star --second"></div><div class="wizard-four-point-star --third"></div></div></div></div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = 'hidden';
    document.getElementById('loading-box').classList.remove("loaded")
  }
}

preloader.initLoading()
window.addEventListener('load',()=> { preloader.endLoading() })
//避免加载时间过长
setTimeout(function(){preloader.endLoading();}, 3000);

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "/img/hexo_loading.gif" data-lazy-src="/img/lenl.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">17</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">25</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 存档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 分享</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/collect/"><i class="fa-fw fas fa-book"></i><span> 大佬们の干货</span></a></li><li><a class="site-page child" href="/resources/"><i class="fa-fw fab fa-dropbox"></i><span> 屯屯鼠の资源</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg fixed" id="page-header" style="background-image: url('https://z4a.net/images/2023/04/22/fcc1d07f3136fe8e818242a6534391c8.md.png')"><nav id="nav"><span id="blog-info"><a href="/" title="LenlBlog"><img class="site-icon" src= "/img/hexo_loading.gif" data-lazy-src="/img/lenl.png"/><span class="site-name">LenlBlog</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 存档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 分享</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/collect/"><i class="fa-fw fas fa-book"></i><span> 大佬们の干货</span></a></li><li><a class="site-page child" href="/resources/"><i class="fa-fw fab fa-dropbox"></i><span> 屯屯鼠の资源</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">基于pdf.js的前后端分离式PDF文件预览实现</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-08-06T02:18:26.000Z" title="发表于 2023-08-06 10:18:26">2023-08-06</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-08-06T03:38:13.513Z" title="更新于 2023-08-06 11:38:13">2023-08-06</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E7%BC%96%E7%A8%8B%E9%9A%8F%E8%AE%B0/">编程随记</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.3k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>10分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="基于pdf.js的前后端分离式PDF文件预览实现"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span><span class="post-meta-separator">|</span><span class="post-meta-commentcount"><i class="far fa-comments fa-fw post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/notes/PdfView/#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/notes/PdfView/" itemprop="commentCount"><i class="fa-solid fa-spinner fa-spin"></i></span></a></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="前言">前言</h2>
<p>为了实现前后端分离模式下的pdf预览，结合网上的一些文章做了一些尝试，折腾了一天终于完成了，在这里记录一下最后正确的实现，以便后续查阅。</p>
<p>前后端分离模式下的文件预览不同于服务端渲染前端，可以通过直接传递文件路径进行文件的预览；而前后端分离模式只能是通过接口让前端下载文件后再进行展示。</p>
<p>当然，这种需求早就是烂大街了，网上应该有很多实现吧。我这么想着，但是搜索出来的结果都是残缺的复制粘贴搬运，根本没法用（唉，这脏乱差的中文互联网环境~），于是东拼西凑，慢慢折腾好了。前端就用大名鼎鼎的 <code>pdf.js</code> 好了，后端 <code>SpringBoot</code> 做一个接口，让前端下载。</p>
<h2 id="前端实现">前端实现</h2>
<h3 id="下载pdf-js">下载pdf.js</h3>
<p>首先前往pdf.js的 <code>github</code> 仓库下载（<a target="_blank" rel="noopener" href="https://github.com/mozilla/pdf.js/releases">仓库release地址</a>）合适的版本，遵从找到的文章，这里我选择了 <code>2.3.313</code> 版本。需要下载的是 <code>pdfjs-2.3.313-dist.zip</code> 这个 <code>Assets</code> 。</p>
<h3 id="引入项目">引入项目</h3>
<p>下载并解压完成后，需要引入项目，并做一些适配性改动。</p>
<p>首先，解压后其结构如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">build</span><br><span class="line">web</span><br><span class="line">LICENSE</span><br></pre></td></tr></table></figure>
<p>在前端目录的 <code>public</code> 下创建文件夹 <code>pdfjs</code> ，这里如果是electron或者比较旧的版本的话需要建在static文件夹下。然后将 <code>build</code> 与 <code>web</code> 两部分拷到新建的文件夹下。这样，就算是项目将 <code>pdf.js</code> 引入了。</p>
<p>接下来为了其可用，还要做一些配置：</p>
<h4 id="解决跨域">解决跨域</h4>
<p><code>pdf.js</code> 会检查源的跨域与否，需要在 <code>web/view.js</code> 中找到如下的代码，并将其注释掉：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> (origin !== viewerOrigin &amp;&amp; protocol !== <span class="string">&quot;blob:&quot;</span>) &#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&quot;file origin does not match viewer&#x27;s&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>此外，后端也需要做一些跨域相关配置的，详见后文后端部分。</p>
<h4 id="支持分页预览">支持分页预览</h4>
<p>预览的pdf可能会比较大，一次性加载显然在部分情况下不合适，因此需要分页传输，这需要做一些更改：</p>
<p>在 <code>web/viewer.js</code> 中搜索 <code>disable</code> ，找到如下配置并修改为如下样子：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&quot;disableAutoFetch&quot;: true, //是否禁用自动获取，true为禁用自动获取，开启分页</span><br><span class="line">&quot;disableFontFace&quot;: false,</span><br><span class="line">&quot;disableRange&quot;: false, //是否禁用range获取文件，false表示支持分页请求头</span><br><span class="line">&quot;disableStream&quot;: true, //分页关键，是否禁用流的形式加载</span><br></pre></td></tr></table></figure>
<h4 id="设置分页尺寸">设置分页尺寸</h4>
<p>在 <code>build/pdf.js</code> 中，找到 <code>DEFAULT_RANGE_CHUNK_SIZE</code> 配置项，其默认是 <code>65536</code> ，我们可以将其配置的大一些，这里我配置成了 <code>65536 * 16</code> 。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">const DEFAULT_RANGE_CHUNK_SIZE = 65536 * 16 ;</span><br></pre></td></tr></table></figure>
<h4 id="请求头加上token">请求头加上token</h4>
<p>在正常的前后端交流中，这里可能是需要登录才能访问，因此需要在请求头加上token。基本上没有文章提到这一点，在我经过数次失败后，发现这一点并苦苦寻找到了相关文件以及代码位置。</p>
<p>在 <code>build/pdf.js</code> 中找到 <code>function createHeaders(httpHeaders)</code> ，并在这里添加token，参考如下：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">createHeaders</span>(<span class="params">httpHeaders</span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> headers = <span class="keyword">new</span> <span class="title class_">Headers</span>();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">const</span> property <span class="keyword">in</span> httpHeaders) &#123;</span><br><span class="line">        <span class="keyword">const</span> value = httpHeaders[property];</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">typeof</span> value === <span class="string">&quot;undefined&quot;</span>) &#123;</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        headers.<span class="title function_">append</span>(property, value);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 自定义 添加了请求的token</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    <span class="keyword">const</span> <span class="title class_">TokenKey</span> = <span class="string">&#x27;TZCJ-ONLINE-TOKEN&#x27;</span></span><br><span class="line">    headers.<span class="title function_">append</span>(<span class="string">&#x27;token&#x27;</span>, sessionStorage.<span class="title function_">getItem</span>(<span class="title class_">TokenKey</span>))</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> headers;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样一来，准备工作就做好了，接下来是预览的实现。</p>
<h3 id="创建预览组件">创建预览组件</h3>
<p>新建一个组件 <code>PdfView</code> ，pdf使用iframe呈现：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;div class=&quot;container&quot;&gt;</span><br><span class="line">    &lt;iframe :src=&quot;pdfUrl&quot; width=&quot;95%&quot; height=&quot;100%&quot;&gt;&lt;/iframe&gt;</span><br><span class="line">  &lt;/div&gt;</span><br><span class="line">&lt;/template&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">export default &#123;</span><br><span class="line">  name: &#x27;PdfView&#x27;,</span><br><span class="line">  data() &#123;</span><br><span class="line">    return &#123;</span><br><span class="line">      // pdf.js中view.html所在位置</span><br><span class="line">      baseUrl: &#x27;/static/pdf/web/viewer.html&#x27;,</span><br><span class="line">      // 要传输给iframe的最终url</span><br><span class="line">      pdfUrl: &#x27;&#x27;,</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  mounted() &#123;&#125;,</span><br><span class="line">  methods: &#123;</span><br><span class="line">    // 传来的参数是后端接口地址，使用encodeURIComponent做一下格式化</span><br><span class="line">    setPdf(url) &#123;</span><br><span class="line">      this.pdfUrl = `$&#123;this.baseUrl&#125;?file=$&#123;encodeURIComponent(url)&#125;`</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;</span><br><span class="line">&lt;/script&gt;</span><br><span class="line">&lt;style scoped lang=&quot;scss&quot;&gt;</span><br><span class="line">.container &#123;</span><br><span class="line">  height: 100vh;</span><br><span class="line">&#125;</span><br><span class="line">&lt;/style&gt;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>然后我们在自己的页面中进行使用，示例如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">    &lt;div class=&quot;container&quot;&gt;</span><br><span class="line">      &lt;pdf-view ref=&quot;PdfView&quot;&gt;&lt;/pdf-view&gt;</span><br><span class="line">    &lt;/div&gt;</span><br><span class="line">&lt;/template&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">import PdfView from &#x27;@/components/PdfView&#x27;</span><br><span class="line">export default &#123;</span><br><span class="line">  name: &#x27;PromiseView&#x27;,</span><br><span class="line">  components: &#123;</span><br><span class="line">    PdfView,</span><br><span class="line">  &#125;,</span><br><span class="line">  data() &#123;</span><br><span class="line">    return &#123;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  mounted() &#123;</span><br><span class="line">      this.openFile(1);</span><br><span class="line">  &#125;,</span><br><span class="line">  methods: &#123;</span><br><span class="line">    openFile(id) &#123;</span><br><span class="line">      const that = this</span><br><span class="line">      setTimeout(() =&gt; &#123;</span><br><span class="line">        // 组合后端请求api</span><br><span class="line">        const api = `$&#123;window.g.BASE_URL&#125;projects/promiseView?id=$&#123;id&#125;`</span><br><span class="line">        that.$refs.PdfView.setPdf(api)</span><br><span class="line">      &#125;, 200);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;</span><br><span class="line">&lt;/script&gt;</span><br><span class="line">&lt;style scoped lang=&quot;scss&quot;&gt;</span><br><span class="line">.container&#123;</span><br><span class="line">  width:950px;</span><br><span class="line">  height: 650px;</span><br><span class="line">  overflow: auto;</span><br><span class="line">&#125;</span><br><span class="line">&lt;/style&gt;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h2 id="后端实现">后端实现</h2>
<p>后端的接口实现这里也费了一番功夫，咱就是说网上那些搬运工搬运的时候自己不试一下的？有问题的代码搬运得到处都是，误人子弟。</p>
<p>总之需要一个 <code>commons-io</code> 的pom依赖：</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!-- https://mvnrepository.com/artifact/commons-io/commons-io 工具--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>commons-io<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-io<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.11.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>然后直接放调整后的接口实现：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">promiseView</span><span class="params">(Integer id,HttpServletResponse response, HttpServletRequest request)</span> &#123;</span><br><span class="line">    <span class="comment">// 数据库查询到项目实体，以便于获取文件路径</span></span><br><span class="line">    <span class="type">Projects</span> <span class="variable">pro</span> <span class="operator">=</span> <span class="built_in">super</span>.getById(id);</span><br><span class="line">    <span class="keyword">if</span>(pro == <span class="literal">null</span>)&#123;</span><br><span class="line">        log.error(<span class="string">&quot;未能找到项目对象&quot;</span>);</span><br><span class="line">        response.setStatus(HttpServletResponse.SC_NOT_FOUND);</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        <span class="comment">// 这里存储的是文件名</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">promise</span> <span class="operator">=</span> pro.getPromise();</span><br><span class="line">        <span class="keyword">if</span>(!StringUtils.hasText(promise))&#123;</span><br><span class="line">            log.error(<span class="string">&quot;未能找到文件名称&quot;</span>);</span><br><span class="line">            response.setStatus(HttpServletResponse.SC_NOT_FOUND);</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            <span class="comment">// 这里是拼接一些自定义常量得到文件在服务器的真实位置</span></span><br><span class="line">            <span class="type">String</span> <span class="variable">path</span> <span class="operator">=</span>  Paths.get(workspace, Consts.UNIT_PROJECT_PROMISE_DIR,promise).toString();</span><br><span class="line">            <span class="type">File</span> <span class="variable">file</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">File</span>(path);</span><br><span class="line">            <span class="keyword">if</span>(!file.exists())&#123;</span><br><span class="line">                log.error(<span class="string">&quot;未能找到文件&quot;</span>);</span><br><span class="line">                response.setStatus(HttpServletResponse.SC_NOT_FOUND);</span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                <span class="type">BufferedInputStream</span> <span class="variable">bis</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">                <span class="type">OutputStream</span> <span class="variable">os</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">                <span class="type">BufferedOutputStream</span> <span class="variable">bos</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">                <span class="type">InputStream</span> <span class="variable">is</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">                <span class="type">boolean</span> firstRequest=<span class="literal">false</span>;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    is = <span class="keyword">new</span> <span class="title class_">FileInputStream</span>(file);</span><br><span class="line">                    bis = <span class="keyword">new</span> <span class="title class_">BufferedInputStream</span>(is);</span><br><span class="line">                    os = response.getOutputStream();</span><br><span class="line">                    bos = <span class="keyword">new</span> <span class="title class_">BufferedOutputStream</span>(os);</span><br><span class="line">                    <span class="comment">// 下载的字节范围</span></span><br><span class="line">                    <span class="type">int</span> startByte, endByte, totalByte;</span><br><span class="line">                    <span class="keyword">if</span> (request != <span class="literal">null</span> &amp;&amp; request.getHeader(<span class="string">&quot;range&quot;</span>) != <span class="literal">null</span>) &#123;</span><br><span class="line">                        <span class="comment">// 断点续传</span></span><br><span class="line">                        String[] range = request.getHeader(<span class="string">&quot;range&quot;</span>).replaceAll(<span class="string">&quot;[^0-9\\-]&quot;</span>, <span class="string">&quot;&quot;</span>).split(<span class="string">&quot;-&quot;</span>);</span><br><span class="line">                        <span class="comment">// 文件总大小</span></span><br><span class="line">                        totalByte = is.available();</span><br><span class="line">                        <span class="comment">// 下载起始位置</span></span><br><span class="line">                        startByte = Integer.parseInt(range[<span class="number">0</span>]);</span><br><span class="line">                        <span class="comment">// 下载结束位置</span></span><br><span class="line">                        <span class="keyword">if</span> (range.length &gt; <span class="number">1</span>) &#123;</span><br><span class="line">                            endByte = Integer.parseInt(range[<span class="number">1</span>]);</span><br><span class="line">                        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                            endByte = totalByte - <span class="number">1</span>;</span><br><span class="line">                        &#125;</span><br><span class="line">                        <span class="comment">// 返回http状态</span></span><br><span class="line">                        response.setStatus(<span class="number">206</span>);</span><br><span class="line">                    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                        <span class="comment">// 首次请求</span></span><br><span class="line">                        firstRequest = <span class="literal">true</span>;</span><br><span class="line">                        <span class="comment">// 正常下载</span></span><br><span class="line">                        <span class="comment">// 文件总大小</span></span><br><span class="line">                        totalByte = is.available();</span><br><span class="line">                        <span class="comment">// 下载起始位置</span></span><br><span class="line">                        startByte = <span class="number">0</span>;</span><br><span class="line">                        <span class="comment">// 下载结束位置</span></span><br><span class="line">                        endByte = totalByte - <span class="number">1</span>;</span><br><span class="line">                        <span class="comment">// 返回http状态</span></span><br><span class="line">                        response.setHeader(<span class="string">&quot;Accept-Ranges&quot;</span>, <span class="string">&quot;bytes&quot;</span>);</span><br><span class="line">                        response.setStatus(<span class="number">200</span>);</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="comment">// 需要下载字节数</span></span><br><span class="line">                    <span class="type">int</span> <span class="variable">length</span> <span class="operator">=</span> endByte - startByte + <span class="number">1</span>;</span><br><span class="line">                    <span class="comment">// 响应头</span></span><br><span class="line">                    response.setHeader(<span class="string">&quot;Access-Control-Allow-Origin&quot;</span>,<span class="string">&quot;*&quot;</span>);</span><br><span class="line">                    response.setHeader(<span class="string">&quot;Accept-Ranges&quot;</span>, <span class="string">&quot;bytes&quot;</span>);</span><br><span class="line">                    response.setHeader(<span class="string">&quot;Content-Range&quot;</span>, <span class="string">&quot;bytes &quot;</span> + startByte + <span class="string">&quot;-&quot;</span> + endByte + <span class="string">&quot;/&quot;</span> + totalByte);</span><br><span class="line">                    response.setContentType(<span class="string">&quot;application/octet-stream&quot;</span>);</span><br><span class="line">                    response.setContentLength(length);</span><br><span class="line">                    <span class="type">int</span> BLOCK_SIZE=<span class="number">1024</span> * <span class="number">64</span> * <span class="number">16</span>;</span><br><span class="line">                    <span class="comment">// 如果是需要分片的且是首次请求，直接返回一个需要切片的信号</span></span><br><span class="line">                    <span class="keyword">if</span>(firstRequest &amp;&amp; totalByte&gt;BLOCK_SIZE)</span><br><span class="line">                        <span class="keyword">return</span>;</span><br><span class="line">                    <span class="comment">// 响应内容</span></span><br><span class="line">                    bis.skip(startByte);</span><br><span class="line">                    <span class="type">int</span> len;</span><br><span class="line">                    <span class="type">byte</span>[] buff = <span class="keyword">new</span> <span class="title class_">byte</span>[BLOCK_SIZE];</span><br><span class="line">                    <span class="keyword">if</span> ((len = bis.read(buff, <span class="number">0</span>, buff.length)) != -<span class="number">1</span>) &#123;</span><br><span class="line">                        bos.write(buff, <span class="number">0</span>, len);</span><br><span class="line">                        bos.flush();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; <span class="keyword">catch</span> (IOException ce)&#123;</span><br><span class="line">                    ce.printStackTrace();</span><br><span class="line">                &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                    IOUtils.closeQuietly(bos);</span><br><span class="line">                    IOUtils.closeQuietly(os);</span><br><span class="line">                    IOUtils.closeQuietly(bis);</span><br><span class="line">                    IOUtils.closeQuietly(is);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如此即可。</p>
<h3 id="网上搬运人错误鉴定">网上搬运人错误鉴定</h3>
<p>以下是网上搬运人到处搬运的后端代码：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Date</span>:2022/2/10 14:00</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Author</span>:lngrid 分页加载pdf</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">loadPDFByPage</span><span class="params">(File file, HttpServletResponse response, HttpServletRequest request)</span> &#123;</span><br><span class="line">    <span class="type">BufferedInputStream</span> <span class="variable">bis</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">    <span class="type">OutputStream</span> <span class="variable">os</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">    <span class="type">BufferedOutputStream</span> <span class="variable">bos</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">    <span class="type">InputStream</span> <span class="variable">is</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        is = <span class="keyword">new</span> <span class="title class_">FileInputStream</span>(file);</span><br><span class="line">        bis = <span class="keyword">new</span> <span class="title class_">BufferedInputStream</span>(is);</span><br><span class="line">        os = response.getOutputStream();</span><br><span class="line">        bos = <span class="keyword">new</span> <span class="title class_">BufferedOutputStream</span>(os);</span><br><span class="line">        <span class="comment">// 下载的字节范围</span></span><br><span class="line">        <span class="type">int</span> startByte, endByte, totalByte;</span><br><span class="line">        <span class="keyword">if</span> (request != <span class="literal">null</span> &amp;&amp; request.getHeader(<span class="string">&quot;range&quot;</span>) != <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="comment">// 断点续传</span></span><br><span class="line">            String[] range = request.getHeader(<span class="string">&quot;range&quot;</span>).replaceAll(<span class="string">&quot;[^0-9\\-]&quot;</span>, <span class="string">&quot;&quot;</span>).split(<span class="string">&quot;-&quot;</span>);</span><br><span class="line">            <span class="comment">// 文件总大小</span></span><br><span class="line">            totalByte = is.available();</span><br><span class="line">            <span class="comment">// 下载起始位置</span></span><br><span class="line">            startByte = Integer.parseInt(range[<span class="number">0</span>]);</span><br><span class="line">            <span class="comment">// 下载结束位置</span></span><br><span class="line">            <span class="keyword">if</span> (range.length &gt; <span class="number">1</span>) &#123;</span><br><span class="line">                endByte = Integer.parseInt(range[<span class="number">1</span>]);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                endByte = totalByte - <span class="number">1</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 返回http状态</span></span><br><span class="line">            response.setStatus(<span class="number">206</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// 正常下载</span></span><br><span class="line">            <span class="comment">// 文件总大小</span></span><br><span class="line">            totalByte = is.available();</span><br><span class="line">            <span class="comment">// 下载起始位置</span></span><br><span class="line">            startByte = <span class="number">0</span>;</span><br><span class="line">            <span class="comment">// 下载结束位置</span></span><br><span class="line">            endByte = totalByte - <span class="number">1</span>;</span><br><span class="line">            <span class="comment">// 返回http状态</span></span><br><span class="line">            response.setHeader(<span class="string">&quot;Accept-Ranges&quot;</span>, <span class="string">&quot;bytes&quot;</span>);</span><br><span class="line">            response.setStatus(<span class="number">200</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 需要下载字节数</span></span><br><span class="line">        <span class="type">int</span> <span class="variable">length</span> <span class="operator">=</span> endByte - startByte + <span class="number">1</span>;</span><br><span class="line">        <span class="comment">// 响应头</span></span><br><span class="line">        response.setHeader(<span class="string">&quot;Accept-Ranges&quot;</span>, <span class="string">&quot;bytes&quot;</span>);</span><br><span class="line">        response.setHeader(<span class="string">&quot;Content-Range&quot;</span>, <span class="string">&quot;bytes &quot;</span> + startByte + <span class="string">&quot;-&quot;</span> + endByte + <span class="string">&quot;/&quot;</span> + totalByte);</span><br><span class="line">        <span class="comment">//            response.setContentType(&quot;application/pdf&quot;);</span></span><br><span class="line">        response.setContentType(<span class="string">&quot;application/octet-stream&quot;</span>);</span><br><span class="line">        response.setContentLength(length);</span><br><span class="line">        <span class="comment">// 响应内容</span></span><br><span class="line">        bis.skip(startByte);</span><br><span class="line">        <span class="type">int</span> <span class="variable">len</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">        <span class="type">byte</span>[] buff = <span class="keyword">new</span> <span class="title class_">byte</span>[<span class="number">1024</span> * <span class="number">64</span>];</span><br><span class="line">        <span class="keyword">while</span> ((len = bis.read(buff, <span class="number">0</span>, buff.length)) != -<span class="number">1</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (length &lt;= len) &#123;</span><br><span class="line">                bos.write(buff, <span class="number">0</span>, length);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                length -= len;</span><br><span class="line">                bos.write(buff, <span class="number">0</span>, len);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="comment">//也可使用try catch关闭IO流</span></span><br><span class="line">        IOUtils.closeQuietly(bos);</span><br><span class="line">        IOUtils.closeQuietly(os);</span><br><span class="line">        IOUtils.closeQuietly(bis);</span><br><span class="line">        IOUtils.closeQuietly(is);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>其问题在于，中间的循环会使得分页传输完全没有什么意义，第一次就会读取文件的全部内容并进行传输写入，还会导致连接关闭后后端报错：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">org.apache.catalina.connector.ClientAbortException: java.io.IOException: 您的主机中的软件中止了一个已建立的连接。</span><br></pre></td></tr></table></figure>
<p>而首次请求仅仅是为了让pdf.js发送后续的分页请求而已。但是如果文件大小本身就小于分片大小时，就需要第一次请求就传输全部数据了。因此对这段代码做了更改，如此既能实现分片预览，又不会出现奇怪的报错了。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://lienle.gitee.io">Lenl</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://lienle.gitee.io/notes/PdfView/">https://lienle.gitee.io/notes/PdfView/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://lienle.gitee.io" target="_blank">LenlBlog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/SpringBoot/">SpringBoot</a><a class="post-meta__tags" href="/tags/Vue/">Vue</a><a class="post-meta__tags" href="/tags/PDF/">PDF</a></div><div class="post_share"><div class="social-share" data-image="https://z4a.net/images/2023/04/22/fcc1d07f3136fe8e818242a6534391c8.md.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wechat.png" target="_blank"><img class="post-qr-code-img" src= "/img/hexo_loading.gif" data-lazy-src="/img/wechat.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/img/alipay.png" target="_blank"><img class="post-qr-code-img" src= "/img/hexo_loading.gif" data-lazy-src="/img/alipay.png" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/notes/electronVue/" title="Electron+Vue项目搭建"><img class="cover" src= "/img/hexo_loading.gif" data-lazy-src="https://z4a.net/images/2023/04/22/fcc1d07f3136fe8e818242a6534391c8.md.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Electron+Vue项目搭建</div></div></a></div><div class="next-post pull-right"><a href="/notes/mysqlInstall/" title="mysql压缩包方式本地安装"><img class="cover" src= "/img/hexo_loading.gif" data-lazy-src="https://z4a.net/images/2023/04/22/fcc1d07f3136fe8e818242a6534391c8.md.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">mysql压缩包方式本地安装</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/notes/chunkFile/" title="基于SpringBoot与Vue的大文件分片上传与流式下载"><img class="cover" src= "/img/hexo_loading.gif" data-lazy-src="https://z4a.net/images/2023/04/22/fcc1d07f3136fe8e818242a6534391c8.md.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-13</div><div class="title">基于SpringBoot与Vue的大文件分片上传与流式下载</div></div></a></div><div><a href="/notes/Knife4j/" title="SpringBoot2集成Knife4j完成api文档自动生成"><img class="cover" src= "/img/hexo_loading.gif" data-lazy-src="https://z4a.net/images/2023/04/22/fcc1d07f3136fe8e818242a6534391c8.md.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-03</div><div class="title">SpringBoot2集成Knife4j完成api文档自动生成</div></div></a></div><div><a href="/notes/wolf2w/" title="wolf2w项目经验_缓存、持久化与参数解析器"><img class="cover" src= "/img/hexo_loading.gif" data-lazy-src="https://z4a.net/images/2023/04/22/fcc1d07f3136fe8e818242a6534391c8.md.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-04-20</div><div class="title">wolf2w项目经验_缓存、持久化与参数解析器</div></div></a></div><div><a href="/notes/tips/" title="SpringBoot一些优雅的小技巧记录"><img class="cover" src= "/img/hexo_loading.gif" data-lazy-src="https://z4a.net/images/2023/04/22/fcc1d07f3136fe8e818242a6534391c8.md.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-03</div><div class="title">SpringBoot一些优雅的小技巧记录</div></div></a></div><div><a href="/notes/wolf2w_2/" title="wolf2w项目经验_站内搜索与接口安全"><img class="cover" src= "/img/hexo_loading.gif" data-lazy-src="https://z4a.net/images/2023/04/22/fcc1d07f3136fe8e818242a6534391c8.md.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-01</div><div class="title">wolf2w项目经验_站内搜索与接口安全</div></div></a></div><div><a href="/notes/electronLearn/" title="Electron学习入门笔记"><img class="cover" src= "/img/hexo_loading.gif" data-lazy-src="https://z4a.net/images/2023/04/22/fcc1d07f3136fe8e818242a6534391c8.md.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-06</div><div class="title">Electron学习入门笔记</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "/img/hexo_loading.gif" data-lazy-src="/img/lenl.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Lenl</div><div class="author-info__description">心有所向，日复一日，必有精进~</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">17</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">25</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/vimianma"><i class="fab fa-github"></i><span>View me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/lienle" target="_blank" title="Gitee"><i class="fa-brands fa-git" style="color: #c71d23;"></i></a><a class="social-icon" href="https://github.com/vimianma" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:lenl412@163.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">本站意在记录个人生活中的所学所感所想所获；<br/>心有所向，日复一日，必有精进~~~<br>请多多指教~</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E7%AB%AF%E5%AE%9E%E7%8E%B0"><span class="toc-number">2.</span> <span class="toc-text">前端实现</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%8B%E8%BD%BDpdf-js"><span class="toc-number">2.1.</span> <span class="toc-text">下载pdf.js</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%95%E5%85%A5%E9%A1%B9%E7%9B%AE"><span class="toc-number">2.2.</span> <span class="toc-text">引入项目</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%A7%A3%E5%86%B3%E8%B7%A8%E5%9F%9F"><span class="toc-number">2.2.1.</span> <span class="toc-text">解决跨域</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%94%AF%E6%8C%81%E5%88%86%E9%A1%B5%E9%A2%84%E8%A7%88"><span class="toc-number">2.2.2.</span> <span class="toc-text">支持分页预览</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%AE%BE%E7%BD%AE%E5%88%86%E9%A1%B5%E5%B0%BA%E5%AF%B8"><span class="toc-number">2.2.3.</span> <span class="toc-text">设置分页尺寸</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%AF%B7%E6%B1%82%E5%A4%B4%E5%8A%A0%E4%B8%8Atoken"><span class="toc-number">2.2.4.</span> <span class="toc-text">请求头加上token</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E9%A2%84%E8%A7%88%E7%BB%84%E4%BB%B6"><span class="toc-number">2.3.</span> <span class="toc-text">创建预览组件</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%90%8E%E7%AB%AF%E5%AE%9E%E7%8E%B0"><span class="toc-number">3.</span> <span class="toc-text">后端实现</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BD%91%E4%B8%8A%E6%90%AC%E8%BF%90%E4%BA%BA%E9%94%99%E8%AF%AF%E9%89%B4%E5%AE%9A"><span class="toc-number">3.1.</span> <span class="toc-text">网上搬运人错误鉴定</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/notes/dockerNotes/" title="Docker备忘笔记"><img src= "/img/hexo_loading.gif" data-lazy-src="https://z4a.net/images/2023/04/22/fcc1d07f3136fe8e818242a6534391c8.md.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Docker备忘笔记"/></a><div class="content"><a class="title" href="/notes/dockerNotes/" title="Docker备忘笔记">Docker备忘笔记</a><time datetime="2024-04-06T13:17:09.000Z" title="发表于 2024-04-06 21:17:09">2024-04-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/notes/mysqlInstall/" title="mysql压缩包方式本地安装"><img src= "/img/hexo_loading.gif" data-lazy-src="https://z4a.net/images/2023/04/22/fcc1d07f3136fe8e818242a6534391c8.md.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="mysql压缩包方式本地安装"/></a><div class="content"><a class="title" href="/notes/mysqlInstall/" title="mysql压缩包方式本地安装">mysql压缩包方式本地安装</a><time datetime="2024-01-03T05:33:33.000Z" title="发表于 2024-01-03 13:33:33">2024-01-03</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/notes/PdfView/" title="基于pdf.js的前后端分离式PDF文件预览实现"><img src= "/img/hexo_loading.gif" data-lazy-src="https://z4a.net/images/2023/04/22/fcc1d07f3136fe8e818242a6534391c8.md.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="基于pdf.js的前后端分离式PDF文件预览实现"/></a><div class="content"><a class="title" href="/notes/PdfView/" title="基于pdf.js的前后端分离式PDF文件预览实现">基于pdf.js的前后端分离式PDF文件预览实现</a><time datetime="2023-08-06T02:18:26.000Z" title="发表于 2023-08-06 10:18:26">2023-08-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/notes/electronVue/" title="Electron+Vue项目搭建"><img src= "/img/hexo_loading.gif" data-lazy-src="https://z4a.net/images/2023/04/22/fcc1d07f3136fe8e818242a6534391c8.md.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Electron+Vue项目搭建"/></a><div class="content"><a class="title" href="/notes/electronVue/" title="Electron+Vue项目搭建">Electron+Vue项目搭建</a><time datetime="2023-05-14T02:36:59.000Z" title="发表于 2023-05-14 10:36:59">2023-05-14</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/notes/chunkFile/" title="基于SpringBoot与Vue的大文件分片上传与流式下载"><img src= "/img/hexo_loading.gif" data-lazy-src="https://z4a.net/images/2023/04/22/fcc1d07f3136fe8e818242a6534391c8.md.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="基于SpringBoot与Vue的大文件分片上传与流式下载"/></a><div class="content"><a class="title" href="/notes/chunkFile/" title="基于SpringBoot与Vue的大文件分片上传与流式下载">基于SpringBoot与Vue的大文件分片上传与流式下载</a><time datetime="2023-05-13T13:57:28.000Z" title="发表于 2023-05-13 21:57:28">2023-05-13</time></div></div></div></div></div></div></main><footer id="footer" style="background: -#484847"><div id="footer-wrap"><div class="copyright">&copy;2023 - 2024 By Lenl</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">Hi, welcome to my blog !</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'dBlOeCLNhBxbSdZO44fRKdBa-gzGzoHsz',
      appKey: 'DCSQoDhPl0UOF7Ix9Imdfd9X',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !false) {
  if (false) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div></body></html>